package com.itboye.jinpuyiyuan.activity.login;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.channel.util.YWLog;
import com.alibaba.mobileim.utility.IMNotificationUtils;
import com.itboye.jinpuyiyuan.MainActivity;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.app.MyApplication;
import com.itboye.jinpuyiyuan.base.BaseActivity;
import com.itboye.jinpuyiyuan.bean.PersonBean;
import com.itboye.jinpuyiyuan.presenter.BranchAddressPresenter;
import com.itboye.jinpuyiyuan.utils.IMKit.LoginSampleHelper;
import com.itboye.jinpuyiyuan.utils.IMKit.NotificationInitSampleHelper;
import com.itboye.jinpuyiyuan.utils.IMKit.UserProfileSampleHelper;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.utils.volley.ResultEntity;
import com.itboye.jinpuyiyuan.widget.FilterUtil;
import com.itboye.jinpuyiyuan.widget.loadingutil.MAlert;
import com.itboye.jinpuyiyuan.wxapi.WXEntryActivity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


import java.util.Observable;
import java.util.Observer;

import static com.itboye.jinpuyiyuan.activity.home.finddoctor.DoctorDetailActivity.TAG;

/**
 * Created by Administrator on 2017/12/19 0019.
 */

public class LoginActivity extends BaseActivity implements Observer {
    private EditText phoneEt,passwordEt;
    private TextView forgetPasswordTv;
    private Button tvLogin;
    private String phoneNumber;
    private ImageView login_wx;
    private BranchAddressPresenter presenter;
    public  LoginSampleHelper loginSampleHelper;

    private String wx_nickname,wx_head,wx_open_id,wx_union_id;

    public BroadcastReceiver receiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final PersonBean personBean= (PersonBean) intent.getSerializableExtra("person");
            FilterUtil.putSharePre(LoginActivity.this.getApplication(),personBean);
            init(personBean.getAlibaichuan_id(), Const.OPEN_APPKEY);
            loginSampleHelper.login_Sample(personBean.getAlibaichuan_id(), personBean.getPassword(), Const.OPEN_APPKEY, new IWxCallback() {
                @Override
                public void onSuccess(Object... objects) {
                    Log.d("login====","success");
//                        MAlert.alert("注册ALI_SDK成功");
                    SPUtils.put(LoginActivity.this, null,
                            Const.PASSWORD, personBean.getPassword());
                    SPUtils.put(LoginActivity.this,null,
                            Const.ALIBAICHUAN,personBean.getAlibaichuan_id());
                }

                @Override
                public void onError(int i, String s) {
                    Log.d("login====","false");
                    Log.d("alert==",i+"=="+s);
                    YWLog.w(TAG, "登录失败，错误码：" + i + "  错误信息：" + s);
                    IMNotificationUtils.getInstance().showToast(LoginActivity.this, s);
                }

                @Override
                public void onProgress(int i) {
                    Log.d("login====","onProgress");

                    Log.d("login====","success");
//                        MAlert.alert("注册ALI_SDK成功");
                    SPUtils.put(LoginActivity.this, null,
                            Const.PASSWORD, personBean.getPassword());
                    SPUtils.put(LoginActivity.this,null,
                            Const.ALIBAICHUAN,personBean.getAlibaichuan_id());
                }
            });

            startActivity(new Intent(LoginActivity.this,MainActivity.class));
            LoginActivity.this.finish();
        }
    };

    @Override
    public void finish() {
        unregisterReceiver(receiver);
    }

    //    private IWXAPI api;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_login);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
         phoneNumber = getIntent().getStringExtra("phone");
        //init SDK 添加消息接受监听
        loginSampleHelper = LoginSampleHelper.getInstance();
        Intent intent = getIntent();
        wx_open_id=intent.getStringExtra("wxapp_openid");
        wx_head=intent.getStringExtra("wx_head");
        wx_nickname=intent.getStringExtra("wx_nickname");
        wx_union_id=intent.getStringExtra("wx_unionid");

        initViewData();
        registerReceiver(receiver,new IntentFilter("loginByWX"));
    }

    private void initViewData() {
        phoneEt.setText(phoneNumber);
        presenter=new BranchAddressPresenter(this);

        passwordEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
              if (actionId== EditorInfo.IME_ACTION_GO||event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER){
                  toLogin();
                  return true;
              }
                return false;
            }
        });



    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()){

            case R.id.tvLogin:

                toLogin();
                break;
            case R.id.login_wx:
                  wxSign();
                break;
            case R.id.forgetPasswordTv:
                Intent intent = new Intent(LoginActivity.this, FindPasswordActivity.class);
                intent.putExtra("phoneNumber",phoneNumber);
                startActivity(intent);
                break;


        }
    }

    private void toLogin() {

        if ("".equals(phoneEt.getText().toString())&&"".equals(passwordEt.getText().toString())){
            MAlert.alert("手机号码和密码不能为空");
        } else if (phoneEt.getText().length()>20||phoneEt.getText().length()<5){
            MAlert.alert("请输入5-20位的手机号码");
        }
        if (wx_union_id!=null||wx_nickname!=null||wx_head!=null||wx_open_id!=null){
            presenter.login(wx_nickname,wx_head,wx_open_id,wx_union_id
                    ,phoneEt.getText().toString(),"itboye"
                    ,passwordEt.getText().toString(),"");
        }else {
            presenter.login("","","",""
                    ,phoneEt.getText().toString(),"itboye"
                    ,passwordEt.getText().toString(),"");
        }
    }


    private static void init(String userId, String appKey){
        //初始化imkit
        LoginSampleHelper.getInstance().initIMKit(userId, appKey);
        //自定义头像和昵称回调初始化(如果不需要自定义头像和昵称，则可以省去)
        UserProfileSampleHelper.initProfileCallback();
        //通知栏相关的初始化
        NotificationInitSampleHelper.init();

    }

    //第三方登录

    //微信登录

    public void wxSign(){

        if (!MyApplication.instatnce.api.isWXAppInstalled()) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        } else {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo_test";
            MyApplication.instatnce.api.sendReq(req);
        }

    }
    @Override
    public void update(Observable o, Object arg) {
        ResultEntity resultEntity = handlerError(arg);
        if (resultEntity!=null){

            if (resultEntity.getEventType()==BranchAddressPresenter.By_UserAccount_loginByMobile_success){
                MAlert.alert("登录成功");
                final PersonBean personBean= (PersonBean) resultEntity.getData();
                Log.d("login==",personBean.getAlibaichuan_id()+"=="+personBean.getPassword()
                        +"uid="+personBean.getUid());
                FilterUtil.putSharePre(LoginActivity.this,personBean);
                init(personBean.getAlibaichuan_id(), Const.OPEN_APPKEY);

                loginSampleHelper.login_Sample(personBean.getAlibaichuan_id(), personBean.getPassword(), Const.OPEN_APPKEY, new IWxCallback() {
                    @Override
                    public void onSuccess(Object... objects) {
                        Log.d("login====","success");
//                        MAlert.alert("注册ALI_SDK成功");
                        SPUtils.put(LoginActivity.this, null,
                                Const.PASSWORD, personBean.getPassword());
                        SPUtils.put(LoginActivity.this,null,
                                Const.ALIBAICHUAN,personBean.getAlibaichuan_id());
                    }

                    @Override
                    public void onError(int i, String s) {
                        Log.d("login====","false");
                        Log.d("alert==",i+"=="+s);
                        YWLog.w(TAG, "登录失败，错误码：" + i + "  错误信息：" + s);
                        IMNotificationUtils.getInstance().showToast(LoginActivity.this, s);
                    }

                    @Override
                    public void onProgress(int i) {
                        Log.d("login====","onProgress");

                        Log.d("login====","success");
//                        MAlert.alert("注册ALI_SDK成功");
                        SPUtils.put(LoginActivity.this, null,
                                Const.PASSWORD, personBean.getPassword());
                        SPUtils.put(LoginActivity.this,null,
                                Const.ALIBAICHUAN,personBean.getAlibaichuan_id());
                    }
                });

                SPUtils.put(LoginActivity.this,null,Const.LOGIN_PASSWORD,passwordEt.getText().toString());
                startActivity(new Intent(LoginActivity.this,MainActivity.class));
                Log.d("role",personBean.getRoles().get(0)+"");
                this.finish();


            }else if (resultEntity.getEventType()==BranchAddressPresenter.By_UserAccount_loginByMobile_fail){
                MAlert.alert(resultEntity.getMsg());
//                MAlert.alert("登录失败");
            }
        }
    }

    public String getSex(int i){
             if (i==1){
                 return "男";
             }else if (i==0){
                 return "女";
             }
             return "";
            }

//
}
